package 读写锁;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2022-09-14 16:27
 **/
public class ReentrantReadWriteLockDemo {

    public static void main(String[] args) {
        final Resource resource = new Resource();
        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            new Thread(() -> {
                resource.write(finalI + "", finalI + "");
            }, String.valueOf(i)).start();
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            new Thread(() -> {
                resource.read("" + finalI);
            }, String.valueOf(i)).start();
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 1; i <= 3; i++) {
            int finalI = i;
            new Thread(() -> {
                resource.write(finalI + "", finalI + "");
            }, "新写线程" + String.valueOf(i)).start();
        }
    }
}

class Resource{

    Map<String, Object> map = new HashMap<>();

    ReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void write(String key, String value) {
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t" + "正在写入");
            map.put(key, value);
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "写入完成");
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public void read(String key) {
        rwLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + "\t正在读取");
            final Object result = map.get(key);
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t完成读取" + "\t" + result);
        }finally {
            rwLock.readLock().unlock();
        }
    }
}
